package znzz.db.util;

import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import znzz.db.entity.MongoConfigVO;
import znzz.db.entity.barcodemaster.BarcodeMaster;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * MongoDB工具类
 * <p/>
 * Created by wangjwm on 2017/7/3.
 */
public enum MongoDBUtil {

    /**
     * 定义一个枚举元素，代表此类的一个实例
     */
    instance;

    // mongodb连接
    private MongoClient mongoClient;

    // mongodb配置
    private MongoConfigVO mongoConfigVO;


    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public MongoConfigVO getMongoConfigVO() {
        return mongoConfigVO;
    }

    static {
        CompositeConfiguration configuration = new CompositeConfiguration();
        try {
            configuration.addConfiguration(new PropertiesConfiguration("properties/mongodb.properties"));
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }

        // 从配置文件中获取属性值
        instance.mongoConfigVO = new MongoConfigVO(
                configuration.getString("host"),
                configuration.getInt("port"),
                configuration.getString("username"),
                configuration.getString("password"),
                configuration.getString("database"),
                configuration.getString("collectionname")
        );

        MongoClientOptions.Builder build = new MongoClientOptions.Builder();
        // 连接池设置为300个连接，默认为100
        build.connectionsPerHost(300);
        // 连接超时设置
        build.connectTimeout(10000);
        build.maxWaitTime(5000);
        // 套接字超时时间，0 无限制
        build.socketTimeout(0);
        // 线程队列数，如果连接线程排满了队列就会抛出 "Out of semaphores to get db" 错误
        build.threadsAllowedToBlockForConnectionMultiplier(5000);
        MongoClientOptions options = build.build();

        // 如果将mongodb设为安全验证模式，需要在客户端提供用户名和密码
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();
        ServerAddress serverAddress = new ServerAddress(
                instance.mongoConfigVO.getIp(),
                instance.mongoConfigVO.getPort()
        );

        addrs.add(serverAddress);

        MongoCredential credential = MongoCredential.
                createScramSha1Credential(
                        instance.mongoConfigVO.getUsername(),
                        instance.mongoConfigVO.getDatabase(),
                        instance.mongoConfigVO.getPassword().toCharArray()
                );

        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        credentials.add(credential);

        instance.mongoClient = new MongoClient(addrs, credentials, options);

    }

    // ---------------------------- 公共方法 ---------------------------- //

    /**
     * 获取DB实例 —— 指定DB
     *
     * @param dbName
     * @return
     */
    public MongoDatabase getDB(String dbName) {
        if (dbName != null && !"".equals(dbName)) {
            MongoDatabase database = mongoClient.getDatabase(dbName);
            return database;
        }
        return null;
    }

    /**
     * 获取collection对象 —— 指定Collection
     *
     * @param dbName
     * @param collName
     * @return
     */
    public MongoCollection<Document> getCollection(String dbName, String collName) {
        if (collName == null || "".equals(collName)) {
            return null;
        }
        if (dbName == null || "".equals(dbName)) {
            return null;
        }
        MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
        return collection;
    }

    /**
     * 查询DB下的所有表名
     *
     * @param dbName
     * @return
     */
    public List<String> getAllCollections(String dbName) {
        MongoIterable<String> colls = getDB(dbName).listCollectionNames();
        List<String> _list = new ArrayList<String>();
        Iterator<String> iterator = colls.iterator();
        while (iterator.hasNext()) {
            _list.add(iterator.next());
        }
        return _list;
    }

    /**
     * 获取所有数据库名称列表
     *
     * @return
     */
    public MongoIterable<String> getAllDBNames() {
        MongoIterable<String> s = mongoClient.listDatabaseNames();
        return s;
    }

    /**
     * 删除一个数据库
     *
     * @param dbName
     */
    public void dropDB(String dbName) {
        getDB(dbName).drop();
    }

    /**
     * 查找对象 —— 根据主键_id
     *
     * @param coll
     * @param id
     * @return
     */
    public Document findById(MongoCollection<Document> coll, String id) {
        Object _idObj = new ObjectId(id);
        Document myDoc = coll.find(Filters.eq("_id", _idObj)).first();
        return myDoc;
    }

    /**
     * 分页查询
     *
     * @param coll
     * @param pageNo
     * @param pageSize
     * @return
     */
    public MongoCursor<Document> findByPage(MongoCollection<Document> coll, int pageNo, int pageSize) {
        Bson orderBy = new BasicDBObject("_id", 1);
        return coll.find().sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
    }

    /**
     * 根据ID删除
     *
     * @param coll
     * @param id
     * @return
     */
    public int deleteById(MongoCollection<Document> coll, String id) {
        int count = 0;
        ObjectId _id = new ObjectId(id);
        Bson filter = Filters.eq("_id", _id);
        DeleteResult deleteResult = coll.deleteOne(filter);
        count = (int) deleteResult.getDeletedCount();
        return count;
    }

    /**
     * 删除表
     *
     * @param dbName
     * @param collName
     */
    public void dropCollection(String dbName, String collName) {
        getDB(dbName).getCollection(collName).drop();
    }

    /**
     * 关闭MongoDB
     */
    public void close() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }

}
